package com.jackie.jedis;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;
import redis.clients.jedis.exceptions.JedisConnectionException;

/**
 * Created by jackie on 2017/3/6.
 */
public class PubSubListener extends JedisPubSub{

    Jedis jedis;

    volatile PubSubListener listener;

    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) {
        super.onUnsubscribe(channel, subscribedChannels);
    }

    @Override
    public void onMessage(String channel, String message) {
        System.out.println("onMessage"+channel+":"+message);
    }

    @Override
    public void onSubscribe(String channel, int subscribedChannels) {
        System.out.println("onSubscribe:"+channel+":"+subscribedChannels);
    }

    @Before
    public void before(){
        jedis=new Jedis();
    }

    @After
    public void after(){
        jedis.close();
    }

    @Test
    public void testPublish(){
        //subscribe是一个阻塞的方法，
        // 在取消订阅该频道前，会一直阻塞在这，只有当取消了订阅才会执行下面的other code
        listener = new PubSubListener();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    jedis.subscribe(listener,"chat");
                }catch (JedisConnectionException exception){
                    if(jedis!=null)
                    jedis.close();
                }

            }
        }).start();
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        while (!listener.isSubscribed());//其他线程订阅后没有写回内存会导致这里一直空转
        listener.unsubscribe("chat");
    }

//    @Test
    public void testSubscribe(){
        jedis.publish("chat","hello");
    }
}
